package com.zhangxin.aiInterview.manager.work_flow.generate_internship_introduction;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zhangxin.aiInterview.common.ErrorCode;
import com.zhangxin.aiInterview.exception.BusinessException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 生成实习介绍
 */
public class GenerateInternshipIntroduction {


    private static final String API_KEY = "cd5245ddf5444cfcedd25b57a29b4c0b";
    private static final String API_SECRET = "MzdhNDEzNzVkMDcyZDhhZTM3MWNjODhj";
    private static final String FLOW_ID = "7343504243880787968";  // 工作流 ID

    public static void main(String[] args) {
        System.out.println(generateInternshipIntroduction("https://zx-1343343346.cos.ap-chongqing.myqcloud.com/ai_interview/resume_pdf/1916016714226561026/0e94MdTR-%E5%BC%A0%E9%91%AB-%E7%A7%91%E5%A4%A7%E8%AE%AF%E9%A3%9E-%E5%85%A8%E6%A0%88%E5%BC%80%E5%8F%91.pdf"));
    }

    /**
     * 生成实习介绍
     * @param resumeUrl
     */
    public static String generateInternshipIntroduction(String resumeUrl) {

        StringBuilder result = new StringBuilder();
        try {
            // 1. 构建请求体 JSON（使用 Hutool）
            JSONObject parameters = new JSONObject();
            //公司+岗位
            parameters.put("AGENT_USER_INPUT","1");
            parameters.put("PDF", resumeUrl);

            JSONObject requestBody = new JSONObject();
            requestBody.put("flow_id", FLOW_ID);
            requestBody.put("uid", "123");
            requestBody.put("stream", false);
            requestBody.put("parameters", parameters);

            // 2. 构建请求 URL
            URL url = new URL("https://xingchen-api.xf-yun.com/workflow/v1/chat/completions");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 3. 设置超时时间（单位：毫秒）
            connection.setConnectTimeout(180000);  // 连接超时：3分钟
            connection.setReadTimeout(180000);     // 读取超时：3分钟（允许等待更久）

            // 4. 设置请求方法和头部
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");

            // 设置 Authorization
            String authorizationHeader = "Bearer " + API_KEY + ":" + API_SECRET;
            connection.setRequestProperty("Authorization", authorizationHeader);
            connection.setDoOutput(true);
            // 5. 发送请求数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.toString().getBytes(StandardCharsets.UTF_8);
                os.write(input);
            }
            // 6. 读取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        if(StrUtil.isBlank(line)) continue;
                        String avatarUrl = getContent(line);
                        result.append(avatarUrl);
                    }
                    return result.toString();
                }
            } else {
                System.out.println("Error: HTTP " + responseCode);
                try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
                    StringBuilder errorResponse = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        errorResponse.append(line);
                    }
                    System.out.println("Error Response: " + errorResponse);
                }
            }
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, e.getMessage());
        }
        return null;
    }
    /**
     * 处理智能体回复内容格式
     * @param jsonStr
     * @return
     */
    public static String getContent(String jsonStr) {
        // 去掉前缀 "data: " 并修正格式
        jsonStr = jsonStr.replaceFirst("^data:\\s*", "").trim();

        // 解析为 JSON 对象
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);

        // 获取 content 字段
        JSONArray choices = jsonObject.getJSONArray("choices");
        JSONObject delta = choices.getJSONObject(0).getJSONObject("delta");
        return delta.getJSONObject("content").getStr("output");
    }
}